<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 卡片布局 -->
      <el-card shadow="never">
        <!-- 面试技巧 ——  头部 -->
        <div class="head">
          <div class="left">
            <!-- 表单  -->
            <el-form
              ref="query"
              :model="query"
              label-width="80px"
              inline
              size="small"
            >
              <el-form-item label="关键字">
                <el-input
                  v-model="query.keyword"
                  placeholder="根据文章标题搜索"
                ></el-input>
              </el-form-item>
              <el-form-item label="状态">
                <el-select v-model="query.state" placeholder="请选择">
                  <!-- v-for 循环 -->
                  <el-option label="启用" value="1"></el-option>
                  <el-option label="禁用" value="0"></el-option>
                </el-select>
              </el-form-item>
            </el-form>

            <div class="btn">
              <!-- 清除 搜索  按钮 -->
              <el-button plain size="small" @click="clearFn">清除</el-button>
              <el-button type="primary" size="small" @click="searchFn"
                >搜索</el-button
              >
            </div>
          </div>

          <div class="right">
            <!-- 新增按钮 -->
            <el-button
              type="success"
              icon="el-icon-edit"
              size="small"
              style="margin-top: -20px"
              @click="addFn"
              >新增技巧</el-button
            >
          </div>
        </div>

        <!-- tips —— 提示 -->
        <div class="tips">
          <i class="el-icon-info" />
          <span class="el-title">数据一共 {{ total }} 条</span>
        </div>

        <!-- 表格 -->
        <template>
          <el-table :data="articlesList" style="width: 100%">
            <el-table-column type="index" label="序号" width="60px">
            </el-table-column>
            <template>
              <el-table-column prop="title" label="文章标题" width="400px">
                <template slot-scope="scope">
                  {{ scope.row.title }}
                  <div
                    v-if="
                      scope.row.videoURL != null && scope.row.videoURL != ''
                    "
                    class="el-icon-film"
                    style="color: blue"
                    @click="videoShowFn(scope.row)"
                  ></div>
                  <div v-else></div>
                </template>
              </el-table-column>
            </template>
            <el-table-column prop="visits" label="阅读数" width="120px">
            </el-table-column>
            <el-table-column prop="username" label="录入人" width="150px">
            </el-table-column>
            <el-table-column prop="createTime" label="录入时间" width="200px">
              <template slot-scope="scope">
                <span>{{ scope.row.createTime | formatTime }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="state"
              label="状态"
              width="100px"
              :formatter="formatter"
            >
            </el-table-column>
            <el-table-column prop="address" label="操作">
              <!-- 操作按钮 -->
              <template v-slot="scope">
                <el-button type="text" size="small" @click="lookFn(scope.row)"
                  >预览</el-button
                >
                <el-button type="text" size="small" @click="isUseFn(scope.row)">
                  {{ scope.row.state === 0 ? "启用" : "禁用" }}
                </el-button>
                <el-button
                  type="text"
                  size="small"
                  @click="modifyFn(scope.row)"
                  :disabled="scope.row.state === 1"
                  >修改</el-button
                >
                <el-button
                  type="text"
                  size="small"
                  @click="delFn(scope.row)"
                  :disabled="scope.row.state === 1"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </template>

        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="query.page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="query.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="text-align: right; margin-top: 20px"
        >
        </el-pagination>

        <!-- 弹框 -->
        <el-dialog
          :title="isEdit ? '修改技巧' : '新增技巧'"
          :visible.sync="isShowDialog"
          width="50%"
          @close="closeFn"
        >
          <el-form
            ref="addArticlesList"
            :model="addArticlesList"
            label-width="80px"
            :rules="rules"
            style="height: 500px"
          >
            <el-form-item label="文章标题" prop="title">
              <el-input
                v-model="addArticlesList.title"
                placeholder="请输入文章标签"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="文章内容"
              prop="articleBody"
              style="height: 280px"
            >
              <!-- 富文本文件 -->
              <quillEditor
                v-model="addArticlesList.articleBody"
                :options="editorOption"
                @blur="checkContent()"
                style="height: 200px"
              ></quillEditor>
            </el-form-item>
            <el-form-item label="视频地址">
              <el-input
                v-model="addArticlesList.videoURL"
                placeholder="请输入视频地址"
              >
              </el-input>
            </el-form-item>
            <el-form-item class="editbtn">
              <el-button @click="cancelFn">取消</el-button>
              <el-button type="primary" @click="onSubmitFn">确认</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>

        <!-- 预览弹框 -->
        <el-dialog title="预览文章" :visible.sync="isLookDialog" width="50%">
          <!-- 使用 -->
          <articles-preview :previewList="previewList"></articles-preview>
        </el-dialog>

        <!-- 视频弹框 -->
        <div class="close" v-if="isVideoShow" @click="closeIconFn">
          <span class="el-icon-close"></span>
        </div>
        <video
          :src="videoURL"
          controls
          autoplay
          width="80%"
          v-if="isVideoShow"
        ></video>
      </el-card>
    </div>
  </div>
</template>

<script>
// 引入 API
import { list, add, update, remove, changeState } from '@/api/hmmm/articles'
// 状态 枚举
import { status } from '@/api/hmmm/constants'

// 引入 富文本
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

// 引入 时间组件
import dayjs from 'dayjs'

// 引入 预览文章组件
import ArticlesPreview from '../components/articles-preview.vue'

export default {
  name: 'articles',
  data () {
    return {
      articlesList: [], // 文章列表
      total: 0, // 总条数
      query: {
        page: 1, // 当前页数
        pagesize: 10, // 页面显示的条数
        keyword: null, // 关键字
        state: null // 状态
      },
      isShowDialog: false, // 显示隐藏
      // 新增文章
      addArticlesList: {
        title: '',
        articleBody: '',
        videoURL: ''
      },
      // 规则
      rules: {
        title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
        articleBody: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ]
      },
      content: '', // 富文本编辑器默认内容
      editorOption: {}, // 富文本编辑器配置
      isEdit: false, // 是否是编辑
      isLookDialog: false, // 是否显示预览弹框
      previewList: {}, // 父传子 —— 文章预览
      isVideoShow: false, // 是否显示视频
      videoURL: ''
    }
  },
  filters: {
    // 格式化入职日期的方法
    formatTime (time) {
      return dayjs(time).format('YYYY-MM-DD hh:mm:ss')
    }
  },
  components: {
    // 注册 富文本
    quillEditor,
    // 注册 预览文章
    ArticlesPreview
  },
  created () {
    // 调用获取列表的方法
    this.getList()
  },

  methods: {
    // 关闭
    closeIconFn () {
      this.isVideoShow = false
    },

    // 视频显示
    videoShowFn (row) {
      this.isVideoShow = true
      this.videoURL = row.videoURL
    },

    // 启用、禁用
    async isUseFn (data) {
      // 定义一个变量
      let state
      // 1 ——> 开启   0 ——> 禁用
      if (data.state === 0) {
        state = 1
      } else {
        state = 0
      }
      // 三元表达式
      // const state = data.state === 0 ? 1 : 0
      // 调用 文章状态 API
      await changeState({ id: data.id, state })
      // 消息提示
      this.$message.success('操作成功')
      // 更新列表
      this.getList()
    },

    // 预览
    lookFn (obj) {
      // 显示预览弹框
      this.isLookDialog = true
      // 忘了这个要干嘛
      this.previewList = obj
    },

    // 删除按钮
    delFn (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // 调用 文章删除 API
          await remove(id)

          // 判断是不是最后一条数据
          if (this.articlesList.length === 1) {
            this.query.page--
            if (this.query.page <= 0) {
              this.query.page = 1
            }
          }

          // 更新列表
          this.getList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    // 关闭
    closeFn () {
      this.$refs.addArticlesList.resetFields()
      this.addArticlesList = {
        id: 0,
        title: '',
        articleBody: '',
        videoURL: ''
      }
    },

    // 修改按钮
    async modifyFn (data) {
      console.log(data)
      // 弹框显示
      this.isShowDialog = true
      // 修改
      this.isEdit = true
      // 数据回填
      this.addArticlesList = { ...data }
    },

    // 确认按钮
    onSubmitFn () {
      this.$refs.addArticlesList.validate(async (valid) => {
        // 验证不通过
        if (!valid) return this.$message.error('请输入内容')
        // 验证通过
        if (this.isEdit) {
          // 调用 文章修改 API
          await update(this.addArticlesList)
          // 提示
          this.$message.success('修改成功')
        } else {
          // 调用  文章添加 API
          await add(this.addArticlesList)
          // 提示
          this.$message.success('新增成功')
        }
        // 更新列表
        this.getList()
        // 隐藏弹框
        this.isShowDialog = false
      })
    },

    // 取消按钮
    cancelFn () {
      // 弹框隐藏
      this.isShowDialog = false
      // 提示
      this.$message('您取消了操作')
    },

    // 新增技巧
    addFn () {
      // 弹框显示
      this.isShowDialog = true
      // 新增
      this.isEdit = false
    },

    // 富文本内容修改验证
    checkContent () {
      this.$refs.addArticlesList.validateField('articleBody')
    },

    // 搜索按钮
    async searchFn () {
      // 调用获取文章方法
      const res = await list(this.query)
      this.articlesList = res.data.items
      this.total = res.data.counts
    },

    // 清除按钮
    clearFn () {
      // 清空关键字
      this.query.keyword = ''
      // 清空状态
      this.query.state = ''
      // 调用 获取文章列表 方法
      this.getList(this.query)
    },

    // 状态
    formatter (row, column, cellValue, index) {
      // 用数组的 find 方法找到 value = 1 的元素，再取出它的 value
      const obj = status.find((item) => item.value === cellValue)
      return obj ? obj.label : '未知'
    },

    // 获取文章列表
    async getList () {
      // 文章列表 API
      const res = await list({
        page: this.query.page,
        pagesize: this.query.pagesize
      })
      // console.log(res)
      this.articlesList = res.data.items
      this.total = res.data.counts
    },

    // 每页显示的条数发生改变时触发
    handleSizeChange (newSize) {
      this.query.pagesize = newSize
      this.getList()
    },

    // 当前页面发生改变时触发
    handleCurrentChange (newPage) {
      this.query.page = newPage
      this.getList()
    }
  }
}
</script>

<style scoped lang='scss'>
.head {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .left {
    display: flex;
  }
  .right {
    margin-top: -20px;
  }
}

.tips {
  line-height: 34px;
  padding: 0px 15px;
  border-radius: 5px;
  border: 1px solid #f4f4f5;
  background: #f4f4f5;
  margin-bottom: 20px;

  .el-title {
    font-size: 13px;
    line-height: 18px;
    color: #909399;
  }
  i {
    margin-right: 10px;
    color: #909399;
  }
}
.editbtn {
  text-align: right;
}
video {
  z-index: 100;
  position: absolute;
  left: 100px;
  top: 60px;
}
.close {
  position: absolute;
  width: 50px;
  height: 50px;
  top: 0px;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.5);
  left: 45%;
  text-align: center;
  line-height: 50px;
  color: #fff;
}
</style>
